<template>
    <div>
        <h1>修改学生</h1>
        <form>
            <table>
                <thead>
                    <tr>
                        <th>姓名：</th>
                        <th> <input type="text" v-model.trim="student.studentName" /></th>
                    </tr>
                    <tr>
                        <th>年龄：</th>
                        <th> <input type="text" v-model.trim="student.studentAge" /></th>
                    </tr>
                    <tr>
                        <th>性别：</th>
                        <th><input type="text" v-model.trim="student.studentSex" /></th>
                    </tr>
                    <tr>
                        <th>所在班级：</th>
                        <th><input type="text" v-model.trim="student.className" /></th>
                    </tr>
                    <tr>
                        <th colspan="2">
                            <input type="button" value="保存" @click="save">
                            <input type="button" value="取消" @click="$router.push('/')">
                        </th>
                    </tr>
                </thead>
            </table>
        </form>
    </div>
</template>

<script setup>
// 引用 api
import { ref, onMounted } from "vue"
import { useRouter, useRoute } from "vue-router"
import axios from "axios"

const router = useRouter();
const route = useRoute();

// 周期函数
onMounted(async () => {
    // 查询请求
    const data = await axios.get(`${api}/${route.params.id}`)

    // 获取学生对象
    if (data.data.code === 200) {
        student.value = data.data.data
    }
})


// 后端 api
const api = 'http://localhost:8000/students';

// 学生对象
const student = ref({
    // 学生姓名
    studentName: '',
    // 学生性别
    studentSex: '',
    // 学生年龄
    studentAge: '',
    // 所在班级
    className: ''
})

// 新增
async function save() {
    // 判断输入框是否都有内容
    for (const key in student.value) {
        if (student.value[key] === '') {
            return
        }
    }

    // 修改请求
    const data = await axios.put(`${api}/${route.params.id}`, student.value)
    if (data.data.code === 200) {
        router.push('/')
    }
}

</script>